package com.tfswx.jcyw.sqlmodel.gic.operators;

import com.alibaba.fastjson.JSON;
import com.tfswx.jcyw.sqlmodel.api.Operator;
import com.tfswx.jcyw.sqlmodel.api.bean.Node;
import com.tfswx.jcyw.sqlmodel.api.bean.jdpz.BdsItem;
import com.tfswx.jcyw.sqlmodel.api.bean.jdpz.FilterJdpz;
import com.tfswx.jcyw.sqlmodel.api.bean.jdpz.ZdItem;
import com.tfswx.jcyw.sqlmodel.api.bean.table.*;
import com.tfswx.jcyw.sqlmodel.api.bean.table.expression.Column;
import com.tfswx.jcyw.sqlmodel.api.bean.table.expression.WhereItem;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 张述江
 * @date 2023/9/7
 */
public class DefaultFilterOperator implements Operator {
    @Override
    public String getName() {
        return "过滤";
    }


    @Override
    public Select operate(Node node, List<Select> pResultList) {
        System.out.println("执行了" + getName() + "操作");
        FilterJdpz jdpz = JSON.parseObject(node.getJdpz(), FilterJdpz.class);

        List<BdsItem> bdsList = jdpz.getBdsList();
        if (bdsList == null) {
            bdsList = new ArrayList<>();
        }

        ParenthesedSelect parenthesedSelect = new ParenthesedSelect(pResultList.get(0));
        PlainSelect plainSelect = new PlainSelect(parenthesedSelect);

        List<ZdItem> zdList = jdpz.getZdList();
        if (zdList == null) {
            zdList = new ArrayList<>();
        }

        List<SelectItem> selectItems = new ArrayList<>();
        for (ZdItem zdItem : zdList) {
            selectItems.add(new SelectItem(new Column(zdItem.getZdbds().toString()), new Alias(zdItem.getZdbm())));
        }
        plainSelect.setSelectItems(selectItems);


        WhereItem whereItem = WhereItem.parse(bdsList);
        plainSelect.setWhere(whereItem);

        return plainSelect;
    }
}
